﻿using System.Web.Routing;
using Orchard.Environment;
using Orchard.Localization;
using Orchard.UI.Navigation;
using NineSeas.Services;
using System;
namespace NineSeas
{
    public class AdminMenu: INavigationProvider
    {
        private readonly Work<RequestContext> _requestContextAccessor;
        private readonly IChapterService _chapterService;
        public string MenuName
        {
            get { return "admin"; }
        }

        public AdminMenu(Work<RequestContext> requestContextAccessor,
                IChapterService chapterService)
        {
            _requestContextAccessor = requestContextAccessor;
            _chapterService = chapterService;
            T = NullLocalizer.Instance;
        }

        private Localizer T { get; set; }

        public void GetNavigation(NavigationBuilder builder)
        {
            var requestContext = _requestContextAccessor.Value;
            var idValue = (string)requestContext.RouteData.Values["id"];
            var id = 0;

            if (!string.IsNullOrEmpty(idValue))
            {
                int.TryParse(idValue, out id);
            }

            var chapterIdText = (string)requestContext.HttpContext.Request["chapterId"];
            var chapterId = 0;

            if (!string.IsNullOrEmpty(chapterIdText))
            {
                int.TryParse(chapterIdText, out chapterId);
            }

            builder

                // Image set
                .AddImageSet("nineseas")

                // "Webshop"
                .Add(item => item

                    .Caption(T("Nineseas"))
                    .Position("1")
                    .LinkToFirstChild(true)

                    // "Books"
                    .Add(subItem =>
                    {
                        subItem.Caption(T("Books"))
                            .Position("1.1")
                            .Action("Index", "BookAdmin", new { area = "NineSeas" })
                            .Add(T("Details"), i => i.Action("Edit", "BookAdmin", new { id }).LocalNav())
                            .Add(T("Chapters"), i => i.Action("Chapters", "BookAdmin", new { id }).LocalNav());

                        if (chapterId > 0)
                        {
                            var chapter = _chapterService.Get(chapterId);
                            var title = !String.IsNullOrEmpty(chapter.Title) ? (chapter.SortOrder + 1) + ". " + chapter.Title : T("Chapter").Text + " " + (chapter.SortOrder + 1);
                            subItem.Add(new LocalizedString(title), i => i.Action("EditChapter", "BookAdmin", new { @id = id, @chapterId = chapterId }).LocalNav());
                        }

                        subItem.Add(T("Create Chapter"), i => i.Action("CreateChapter", "BookAdmin", new { id }).LocalNav());
                    })

                );
        }
    }
}